package com.lpdemilis.pokermanager;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

public class AuthorizeUserActivity extends Activity implements MyAsyncListener {
	private User user;
	private int groupindex;
	private int groupid;
	protected CustomHttpClient client;
	private LinearLayout eventUsersLinearLayout;
	protected String SERVER_URL;

	private ArrayList<Number> useridsArrayList;
	private ArrayList<String> usernamesArrayList;
	private ArrayList<String> emailsArrayList;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_authorizeuser);

		if (Build.MANUFACTURER.equals("unknown")) {
			SERVER_URL = this.getString(R.string.URL_local);
		} else {
			SERVER_URL = this.getString(R.string.URL);
		}

		TextView activityTitleTextView = (TextView) findViewById(R.id.activityTitleTextView);
		Typeface titleTypeface = Typeface.createFromAsset(getAssets(),
				"fonts/POKERPN.TTF");
		activityTitleTextView.setTypeface(titleTypeface);

		user = (User) getIntent().getSerializableExtra("user");
		groupindex = getIntent().getIntExtra("groupindex", 0);
		groupid = getIntent().getIntExtra("groupid", 0);

		eventUsersLinearLayout = (LinearLayout) findViewById(R.id.eventUsersLinearLayout);

		getUnauthorizedUsers();
	}

	public enum ActionsEnum {
		getUnauthorizedUsers, authorizeUser, error;
	}

	@Override
	public void executeReturn(String returnValue) {
		String[] returnArray;
		returnArray = returnValue.split("##");

		ActionsEnum action;

		try {
			action = ActionsEnum.valueOf(returnArray[0]);
		} catch (Exception e) {
			action = ActionsEnum.error;
		}

		switch (action) {
		case getUnauthorizedUsers:
			getUnauthorizedUsersReturn(returnArray);
			break;
		case authorizeUser:
			authorizeUserReturn(returnArray);
			break;
		case error:
			errorReturn(returnArray);
			break;
		}
	}

	private void errorReturn(String[] returnArray) {
		getUnauthorizedUsers();
	}

	private void getUnauthorizedUsersReturn(String[] returnArray) {
		eventUsersLinearLayout.removeAllViewsInLayout();
		useridsArrayList = new ArrayList<Number>();
		usernamesArrayList = new ArrayList<String>();
		emailsArrayList = new ArrayList<String>();

		if (returnArray.length > 1) {
			String[] userids = returnArray[2].trim().split("@@");

			if (!userids[0].equals("")) {
				for (int i = 0; i < userids.length; i++) {
					useridsArrayList.add(Integer.valueOf(userids[i]));
				}
			}

			String[] usernames = returnArray[4].trim().split("@@");

			if (!usernames[0].equals("")) {
				for (int i = 0; i < usernames.length; i++) {
					usernamesArrayList.add(usernames[i]);
				}
			}

			String[] emails = returnArray[6].trim().split("@@");

			if (!emails[0].equals("")) {
				for (int i = 0; i < emails.length; i++) {
					emailsArrayList.add(emails[i]);
				}
			}
		}

		updateInterface();
	}

	private void authorizeUserReturn(String[] returnArray) {
		getUnauthorizedUsers();
	}

	private void updateInterface() {
		// update interface

		ArrayList<LinearLayout> usersLinearLayouts = new ArrayList<LinearLayout>();
		ArrayList<TextView> usersNamesTextViews = new ArrayList<TextView>();
		ArrayList<Button> authorizeUserButtons = new ArrayList<Button>();

		eventUsersLinearLayout.removeAllViewsInLayout();

		if (useridsArrayList.size() == 0) {
			TextView noUsersTextView = new TextView(this);
			noUsersTextView.setText(this.getString(R.string.no_unauthorized_users));
			eventUsersLinearLayout.addView(noUsersTextView);
			
		} else {
			for (int i = 0; i < useridsArrayList.size(); i++) {
				usersLinearLayouts.add(i, new LinearLayout(this));
				usersLinearLayouts.get(i).setLayoutParams(
						new LinearLayout.LayoutParams(
								LayoutParams.MATCH_PARENT, Utils
										.convertToPixel(60, this)));
				usersLinearLayouts.get(i).setGravity(Gravity.CENTER_VERTICAL);
				usersLinearLayouts.get(i).setPadding(
						Utils.convertToPixel(10, this), 0,
						Utils.convertToPixel(10, this), 0);

				usersNamesTextViews.add(i, new TextView(this));
				usersNamesTextViews.get(i).setTextAppearance(this,
						R.style.custom_textview);
				usersNamesTextViews.get(i).setPadding(0, 0,
						Utils.convertToPixel(10, this), 0);
				usersNamesTextViews.get(i).setLayoutParams(
						new LinearLayout.LayoutParams(
								LayoutParams.MATCH_PARENT,
								LayoutParams.WRAP_CONTENT, (float) 1));
				usersNamesTextViews.get(i).setText(usernamesArrayList.get(i));

				usersLinearLayouts.get(i).addView(usersNamesTextViews.get(i));

				authorizeUserButtons.add(i,
						Utils.setButtonStyle_opal(this, new Button(this)));
				authorizeUserButtons.get(i).setText(
						this.getString(R.string.authorizeuser_button));
				authorizeUserButtons.get(i).setLayoutParams(
						new LinearLayout.LayoutParams(Utils.convertToPixel(100,
								this), Utils.convertToPixel(40, this)));
				authorizeUserButtons.get(i).setPadding(0, 0, 0, 0);
				authorizeUserButtons.get(i).setOnClickListener(
						authorizeUserButtonClickListener);
				authorizeUserButtons.get(i).setId(
						useridsArrayList.get(i).intValue());

				usersLinearLayouts.get(i).addView(authorizeUserButtons.get(i));

				if (i % 2 == 0) {
					usersLinearLayouts.get(i).setBackgroundResource(
							R.drawable.faixa);
				} else {
					usersLinearLayouts.get(i).setBackgroundResource(
							R.drawable.faixa1);
				}

				eventUsersLinearLayout.addView(usersLinearLayouts.get(i));
			}
		}
	}

	@Override
	public void onBackPressed() {
		Intent intent = new Intent(AuthorizeUserActivity.this,
				MainActivity.class);
		intent.putExtra("user", user);
		intent.putExtra("groupindex", groupindex);
		AuthorizeUserActivity.this.startActivity(intent);
		AuthorizeUserActivity.this.finish();
	}

	View.OnClickListener authorizeUserButtonClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			authorizeUser(groupid, v.getId(), user.getId());
		}
	};

	public void getUnauthorizedUsers() {
		try {
			client = new CustomHttpClient(this,
					this.getString(R.string.wait_message), true);
			String action = ActionsEnum.getUnauthorizedUsers.toString();
			String paramName1 = "groupid";
			String paramValue1 = String.valueOf(groupid);
			client.execute(SERVER_URL, action, paramName1, paramValue1);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void authorizeUser(int groupid, int userid, int usermodified) {
		try {
			client = new CustomHttpClient(this,
					this.getString(R.string.wait_message), true);
			String action = ActionsEnum.authorizeUser.toString();
			String paramName1 = "groupid";
			String paramValue1 = String.valueOf(groupid);
			String paramName2 = "userid";
			String paramValue2 = String.valueOf(userid);
			String paramName3 = "usermodified";
			String paramValue3 = String.valueOf(usermodified);
			client.execute(SERVER_URL, action, paramName1, paramValue1,
					paramName2, paramValue2, paramName3, paramValue3);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.activity_authorizeuser, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.menu_logoff:
			Intent intent = new Intent(AuthorizeUserActivity.this,
					LoginActivity.class);
			AuthorizeUserActivity.this.startActivity(intent);
			AuthorizeUserActivity.this.finish();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
}
